import Overlay from 'ol/Overlay';
import { DragPan } from 'ol/interaction';

/**
 * OpenLayers Popup
 */
export default class Popup extends Overlay {

  constructor(opt_options) {

    const options = opt_options || {};
    if (options.autoPan === undefined)options.autoPan = true;
    if (options.autoPanAnimation === undefined) {
      options.autoPanAnimation = {
        duration: 250
      };
    }
    options.stopEvent = false;
    options.dragging = false;
    let element = document.createElement('div');

    options.element = element;
    super(options);
    this.container = element;
    this.container.className = 'ol-popup';

    this.content = document.createElement('div');
    this.content.className = 'ol-popup-content';
    this.container.appendChild(this.content);

    let dragPan;

    options.map.getInteractions().forEach((interaction)=>{
      if (interaction instanceof DragPan) {
        dragPan = interaction;
      }
    });
    let clickPosition = '';  //点击处坐标
    let isClickPosition = true; //是否获取点击处坐标

    this.content.addEventListener('mousedown', (evt)=> {
      this.content.style.cursor = 'move';
      dragPan.setActive(false);
      this.set('dragging', true);
      console.info('start dragging');
    });

    options.map.on('pointermove', (evt)=> {
      let coordinate = evt.coordinate;
      if(isClickPosition)clickPosition = coordinate;
      if (this.get('dragging')) {
        isClickPosition = false;
        let x = clickPosition[0] - coordinate[0];
        let y = clickPosition[1] - coordinate[1];
        let newPoint = [this.lastPosition[0]-x,this.lastPosition[1]-y]
        //如果设置偏移减去偏移
        // let dd2=options.map.getPixelFromCoordinate(evt.coordinate);
        // console.log(dd2,'=dd2');
        // let newX=dd2[0]-0;//减去偏移量
        // let newY=dd2[1]-0;
        // let newPoint=options.map.getCoordinateFromPixel([newX,newY]);
        this.setPosition(newPoint);
      }
    });
    options.map.on('pointerup', (evt)=> {
      if (this.get('dragging') === true) {
        console.info('stop dragging');
        isClickPosition = true;
        this.lastPosition = this.getPosition();
        this.content.style.cursor = 'auto';

        dragPan.setActive(true);
        this.set('dragging', false);
      }
    });
  }


  show(coord, html) {
    if (html instanceof HTMLElement) {
      this.content.innerHTML = "";
      this.content.appendChild(html);
    } else {
      this.content.innerHTML = html;
    }
    this.container.style.display = 'block';
    this.content.scrollTop = 0;
    this.setPosition(coord);
    this.lastPosition = coord;
    return this;
  }

  hide() {
    this.container.style.display = 'none';
    return this;
  }

  isOpened() {
    return this.container.style.display = 'block';
  }
}
